package geradatawarehouse.dao.postgres;

import geradatawarehouse.bean.Turma;
import geradatawarehouse.dao.postgres.abs.PostgresDAO;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class TurmaPostgresDAO extends PostgresDAO {
	private static final String TRUNCATE_TURMA = "truncate turma";

	protected TurmaPostgresDAO() throws IOException {
		super();
	}

	private void fillTable(final List<Turma> lista, final Connection conn)
			throws SQLException {

		final StringBuilder sb = new StringBuilder();

		sb.append("INSERT INTO turma("
				+ "\"cod_serie\", \"ano_sem\", \"cod_curso\""
				+ ", \"cod_unidade\", \"cod_turno\"," + "codigo, letra, nome)"
				+ "VALUES ");

		for (final Turma t : lista) {
			sb.append("(");
			sb.append(t.getCodSerie());
			sb.append(", ");
			sb.append(t.getAnoSem());
			sb.append(", ");
			sb.append(t.getCodCurso());
			sb.append(", '");
			sb.append(this.escape(t.getCodUnidade()));
			sb.append("', '");
			sb.append(this.escape("" + t.getCodTurno()));
			sb.append("', ");
			sb.append(t.getCodigo());
			sb.append(", '");
			sb.append(this.escape(t.getLetra()));
			sb.append("', '");
			sb.append(this.escape(t.getNome()));
			sb.append("'), ");

		}

		String query = sb.toString();

		query = query.substring(0, query.length() - ", ".length());

		final Statement smt = conn.createStatement();

		smt.executeUpdate(query);

	}

	public void replaceAll(final List<Turma> lista) throws SQLException {
		Connection conn = null;

		try {
			conn = this.buildConnection();

			conn.setAutoCommit(false);

			this.truncateTable(conn);

			this.fillTable(lista, conn);

			conn.commit();
		} catch (final SQLException e) {
			conn.rollback();
			throw e;
		} finally {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		}
	}

	private void truncateTable(final Connection conn) throws SQLException {

		final Statement smt = conn.createStatement();

		smt.executeUpdate(TurmaPostgresDAO.TRUNCATE_TURMA);

	}
}
